<template>
  <div class="ai-chat-fullscreen">
    <!-- 简约头部 -->
    <div class="chat-header">
      <div class="header-title">
        <el-icon><ChatDotRound /></el-icon>
        <span>AI 助手</span>
      </div>
      <div class="header-actions">
        <el-tooltip content="清空对话" placement="bottom">
          <el-button text circle @click="clearChat">
            <el-icon><Delete /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 消息区域 -->
    <div class="messages-area" ref="messagesContainer">
      <!-- 空状态 -->
      <div v-if="messages.length === 0" class="empty-state">
        <el-icon class="empty-icon"><ChatDotRound /></el-icon>
        <p>开始对话...</p>
      </div>

      <!-- 消息列表 -->
      <div
        v-for="(msg, index) in messages"
        :key="index"
        class="message-bubble"
        :class="msg.role"
      >
        <div class="bubble-content">
          <!-- 图片附件 -->
          <div v-if="msg.images && msg.images.length > 0" class="message-images">
            <el-image
              v-for="(img, idx) in msg.images"
              :key="idx"
              :src="img"
              fit="cover"
              class="msg-image"
              :preview-src-list="msg.images"
            />
          </div>
          
          <!-- 文件附件 -->
          <div v-if="msg.files && msg.files.length > 0" class="message-files">
            <div v-for="(file, idx) in msg.files" :key="idx" class="file-item">
              <el-icon><Document /></el-icon>
              <span>{{ file.name }}</span>
            </div>
          </div>
          
          <!-- 文本内容 -->
          <div v-if="msg.content" class="message-text" v-html="formatMessage(msg.content)"></div>
          
          <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
        </div>
      </div>

      <!-- AI思考中 -->
      <div v-if="loading" class="message-bubble assistant thinking">
        <div class="bubble-content">
          <div class="typing-dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <!-- 附件预览 -->
      <div v-if="attachments.length > 0" class="attachments-preview">
        <div v-for="(file, index) in attachments" :key="index" class="attachment-item">
          <el-image 
            v-if="file.type.startsWith('image/')"
            :src="file.preview"
            fit="cover"
            class="preview-image"
          />
          <div v-else class="preview-file">
            <el-icon><Document /></el-icon>
            <span>{{ file.name }}</span>
          </div>
          <el-icon class="remove-btn" @click="removeAttachment(index)">
            <Close />
          </el-icon>
        </div>
      </div>
      
      <!-- 输入框 -->
      <div class="input-wrapper">
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="1"
          :autosize="{ minRows: 2, maxRows: 8 }"
          placeholder="输入消息...（回车发送，Shift+回车换行）"
          :disabled="loading"
          class="message-input"
          @keydown.enter.exact.prevent="sendMessage"
          @keydown.shift.enter.exact="handleShiftEnter"
        />
        
        <div class="input-tools">
          <el-upload
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            accept="image/*,.pdf,.doc,.docx,.txt"
            multiple
          >
            <el-button text circle>
              <el-icon><Paperclip /></el-icon>
            </el-button>
          </el-upload>
          
          <el-button 
            type="primary"
            circle
            @click="sendMessage"
            :loading="loading"
            :disabled="!userInput.trim() && attachments.length === 0"
          >
            <el-icon><Promotion /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ChatDotRound, Delete, Promotion, Document, Paperclip, Close } from '@element-plus/icons-vue'
import { aiApi } from '@/api/ai'

// 响应式数据
const userInput = ref('')
const messages = ref([])
const loading = ref(false)
const messagesContainer = ref(null)
const sessionId = ref('')
const attachments = ref([]) // 附件列表

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 格式化消息内容（支持Markdown）
const formatMessage = (content) => {
  if (!content) return ''
  
  let formatted = content
  
  // 1. 处理代码块（```）
  formatted = formatted.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
    const language = lang || 'plaintext'
    const escapedCode = code
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
    return `<pre class="code-block"><code class="language-${language}">${escapedCode}</code></pre>`
  })
  
  // 2. 处理行内代码
  formatted = formatted.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')
  
  // 3. 处理换行（在代码块之外）
  formatted = formatted.replace(/\n/g, '<br/>')
  
  // 4. 处理粗体
  formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  
  // 5. 处理斜体
  formatted = formatted.replace(/\*(.*?)\*/g, '<em>$1</em>')
  
  // 6. 处理标题
  formatted = formatted.replace(/###\s+(.*?)(<br\/>|$)/g, '<h3>$1</h3>')
  formatted = formatted.replace(/##\s+(.*?)(<br\/>|$)/g, '<h2>$1</h2>')
  
  // 7. 处理列表项
  formatted = formatted.replace(/^[•\-]\s+/gm, '• ')
  
  // 8. 处理表格（简单的markdown表格）
  formatted = formatted.replace(/\|(.+)\|/g, (match) => {
    const cells = match.split('|').filter(cell => cell.trim())
    const cellsHtml = cells.map(cell => `<td>${cell.trim()}</td>`).join('')
    return `<tr>${cellsHtml}</tr>`
  })
  
  // 9. 处理emoji和特殊符号
  formatted = formatted.replace(/✅/g, '<span class="emoji">✅</span>')
  formatted = formatted.replace(/❌/g, '<span class="emoji">❌</span>')
  formatted = formatted.replace(/📊/g, '<span class="emoji">📊</span>')
  formatted = formatted.replace(/👤/g, '<span class="emoji">👤</span>')
  
  return formatted
}

// 处理文件选择
const handleFileChange = (file) => {
  const maxSize = 10 * 1024 * 1024 // 10MB
  
  if (file.size > maxSize) {
    ElMessage.warning('文件大小不能超过10MB')
    return
  }
  
  // 创建文件预览
  const fileData = {
    name: file.name,
    type: file.raw.type,
    size: file.size,
    file: file.raw
  }
  
  // 如果是图片，生成预览
  if (file.raw.type.startsWith('image/')) {
    const reader = new FileReader()
    reader.onload = (e) => {
      fileData.preview = e.target.result
      attachments.value.push(fileData)
    }
    reader.readAsDataURL(file.raw)
  } else {
    attachments.value.push(fileData)
  }
}

// 移除附件
const removeAttachment = (index) => {
  attachments.value.splice(index, 1)
}

// 处理Shift+回车（换行）
const handleShiftEnter = (event) => {
  // Shift+回车时插入换行符
  const textarea = event.target
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  
  userInput.value = userInput.value.substring(0, start) + '\n' + userInput.value.substring(end)
  
  // 恢复光标位置
  nextTick(() => {
    textarea.selectionStart = textarea.selectionEnd = start + 1
  })
}

// 发送消息
const sendMessage = async () => {
  if ((!userInput.value.trim() && attachments.value.length === 0) || loading.value) return

  const messageText = userInput.value.trim()
  
  // 构建消息对象
  const userMessage = {
    role: 'user',
    content: messageText,
    timestamp: Date.now()
  }
  
  // 添加图片
  const images = attachments.value
    .filter(f => f.type.startsWith('image/'))
    .map(f => f.preview)
  if (images.length > 0) {
    userMessage.images = images
  }
  
  // 添加文件
  const files = attachments.value
    .filter(f => !f.type.startsWith('image/'))
    .map(f => ({ name: f.name, size: f.size }))
  if (files.length > 0) {
    userMessage.files = files
  }
  
  // 添加用户消息
  messages.value.push(userMessage)
  
  // 清空输入和附件
  userInput.value = ''
  attachments.value = []
  scrollToBottom()
  
  try {
    loading.value = true
    
    // 构建请求数据
    const requestData = {
      message: messageText,
      sessionId: sessionId.value,
      history: messages.value.slice(-10)
    }
    
    // 添加图片（Base64格式）
    if (images.length > 0) {
      requestData.images = images
    }
    
    // 添加文件信息
    if (files.length > 0) {
      requestData.files = files
    }
    
    const response = await aiApi.sendMessage(requestData)
    
    if (response.data && response.data.success) {
      // 更新sessionId
      if (response.data.sessionId) {
        sessionId.value = response.data.sessionId
      }
      
      // 添加AI回复
      messages.value.push({
        role: 'assistant',
        content: response.data.message,
        timestamp: Date.now()
      })
      
      scrollToBottom()
    } else {
      ElMessage.error(response.data.error || 'AI回复失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请检查网络连接')
    
    // 添加错误消息
    messages.value.push({
      role: 'assistant',
      content: '抱歉，我遇到了一些问题。请稍后再试。',
      timestamp: Date.now()
    })
  } finally {
    loading.value = false
    scrollToBottom()
  }
}

// 清空对话
const clearChat = async () => {
  try {
    if (sessionId.value) {
      await aiApi.clearSession(sessionId.value)
    }
    messages.value = []
    sessionId.value = ''
    ElMessage.success('对话已清空')
  } catch (error) {
    console.error('清空对话失败:', error)
    messages.value = []
    sessionId.value = ''
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 加载历史记录
const loadHistory = async () => {
  try {
    const response = await aiApi.getUserHistory('default_user', 50)
    if (response.data && Array.isArray(response.data)) {
      messages.value = response.data
      scrollToBottom()
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

// 页面挂载时加载历史
onMounted(() => {
  loadHistory()
})
</script>

<style scoped lang="scss">
// 全屏容器
.ai-chat-fullscreen {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  background: #fafafa;
}

// 简约头部
.chat-header {
  height: 56px;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  border-bottom: 1px solid #e5e7eb;
  flex-shrink: 0;

  .header-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 16px;
    font-weight: 500;
    color: #303133;

    .el-icon {
      font-size: 24px;
      color: #409eff;
    }
  }

  .header-actions {
    .el-button {
      color: #909399;

      &:hover {
        color: #303133;
      }
    }
  }
}

// 消息区域
.messages-area {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

// 空状态
.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;

  .empty-icon {
    font-size: 48px;
    margin-bottom: 12px;
    opacity: 0.5;
  }

  p {
    font-size: 14px;
    margin: 0;
  }
}

// 消息气泡
.message-bubble {
  display: flex;
  animation: fadeIn 0.3s ease;

  &.user {
    justify-content: flex-end;

    .bubble-content {
      background: #409eff;
      color: white;
      border-radius: 18px 18px 4px 18px;

      .message-time {
        color: rgba(255, 255, 255, 0.7);
      }
      
      // 用户消息中的代码块样式
      .message-text {
        :deep(.code-block) {
          background: rgba(0, 0, 0, 0.2);
          
          code {
            color: rgba(255, 255, 255, 0.95);
          }
        }
        
        :deep(.inline-code) {
          background: rgba(0, 0, 0, 0.2);
          color: #fff;
        }
        
        :deep(strong) {
          color: #fff;
        }
      }
    }
  }

  &.assistant {
    justify-content: flex-start;

    .bubble-content {
      background: white;
      color: #303133;
      border-radius: 18px 18px 18px 4px;
      border: 1px solid #e5e7eb;
    }
  }

  &.thinking {
    .bubble-content {
      padding: 16px 20px;
    }
  }

  .bubble-content {
    max-width: 70%;
    padding: 12px 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

    .message-images {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 8px;

      .msg-image {
        width: 200px;
        height: 200px;
        border-radius: 8px;
        cursor: pointer;
      }
    }

    .message-files {
      margin-bottom: 8px;

      .file-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px;
        background: rgba(0, 0, 0, 0.05);
        border-radius: 8px;
        font-size: 13px;

        .el-icon {
          font-size: 18px;
        }
      }
    }

    .message-text {
      font-size: 14px;
      line-height: 1.6;
      word-wrap: break-word;

      // 行内代码样式
      :deep(.inline-code) {
        background: rgba(0, 0, 0, 0.08);
        padding: 2px 6px;
        border-radius: 4px;
        font-family: 'Menlo', 'Monaco', 'Courier New', monospace;
        font-size: 13px;
        color: #e83e8c;
      }
      
      // 代码块样式
      :deep(.code-block) {
        background: #282c34;
        border-radius: 8px;
        padding: 16px;
        margin: 12px 0;
        overflow-x: auto;
        
        code {
          font-family: 'Menlo', 'Monaco', 'Courier New', monospace;
          font-size: 13px;
          line-height: 1.5;
          color: #abb2bf;
          display: block;
          white-space: pre;
          
          // JSON语法高亮
          &.language-json {
            color: #98c379;
          }
        }
      }

      :deep(strong) {
        font-weight: 600;
        color: #303133;
      }

      :deep(h2), :deep(h3) {
        margin: 12px 0 8px 0;
        font-weight: 600;
        color: #303133;
      }
      
      :deep(h2) {
        font-size: 18px;
        border-bottom: 2px solid #409eff;
        padding-bottom: 8px;
      }
      
      :deep(h3) {
        font-size: 16px;
      }
      
      // Emoji样式
      :deep(.emoji) {
        font-size: 18px;
        margin: 0 2px;
      }
      
      // 表格样式
      :deep(table) {
        border-collapse: collapse;
        margin: 12px 0;
        width: 100%;
        
        td {
          border: 1px solid #e5e7eb;
          padding: 8px 12px;
        }
        
        tr:first-child td {
          background: #f5f7fa;
          font-weight: 600;
        }
      }
    }

    .message-time {
      display: block;
      font-size: 11px;
      margin-top: 6px;
      opacity: 0.6;
      text-align: right;
    }

    .typing-dots {
      display: flex;
      gap: 6px;
      padding: 4px 0;

      span {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #909399;
        animation: bounce 1.4s infinite;

        &:nth-child(1) {
          animation-delay: 0s;
        }
        &:nth-child(2) {
          animation-delay: 0.2s;
        }
        &:nth-child(3) {
          animation-delay: 0.4s;
        }
      }
    }
  }
}

// 输入容器
.input-container {
  background: white;
  border-top: 1px solid #e5e7eb;
  padding: 16px 24px;
  flex-shrink: 0;

  .attachments-preview {
    display: flex;
    gap: 12px;
    margin-bottom: 12px;
    flex-wrap: wrap;

    .attachment-item {
      position: relative;
      width: 80px;
      height: 80px;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #e5e7eb;

      .preview-image {
        width: 100%;
        height: 100%;
      }

      .preview-file {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background: #f5f7fa;
        font-size: 11px;
        color: #606266;

        .el-icon {
          font-size: 24px;
          margin-bottom: 4px;
        }

        span {
          max-width: 70px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .remove-btn {
        position: absolute;
        top: 4px;
        right: 4px;
        width: 18px;
        height: 18px;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 50%;
        color: white;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;

        &:hover {
          background: rgba(0, 0, 0, 0.8);
        }
      }
    }
  }

  .input-wrapper {
    display: flex;
    gap: 12px;
    align-items: flex-end;

    .message-input {
      flex: 1;

      :deep(.el-textarea__inner) {
        border: 1px solid #e5e7eb;
        border-radius: 20px;
        padding: 10px 16px;
        font-size: 14px;
        resize: none;

        &:focus {
          border-color: #409eff;
        }
      }
    }

    .input-tools {
      display: flex;
      gap: 8px;
      align-items: center;

      .el-button {
        &:not(.el-button--primary) {
          color: #606266;

          &:hover {
            color: #409eff;
          }
        }

        &.el-button--primary {
          width: 40px;
          height: 40px;
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-8px);
  }
}
</style>

